package com.axend.aerosense.dev.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.bean.BaseBean;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.utils.ThreadPoolUtils;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.WsApi;
import com.axend.aerosense.common.base.IHostLayout;
import com.axend.aerosense.common.base.ITitle;
import com.axend.aerosense.common.bean.RadarBean;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.ui.CustomTipsPopupWindow;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.dev.BR;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.databinding.DevFragmentBedBreatheBinding;
import com.axend.aerosense.dev.entity.RadarInsatllTipsBean;
import com.axend.aerosense.dev.impl.ICustomToolBar;
import com.axend.aerosense.dev.viewmodel.BedAndBreatheViewModel;
import com.axend.aerosense.network.websocket.JWebSocketClient;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;

import org.jetbrains.annotations.NotNull;

import java.net.URI;

public class DevBedAndBreatheFragment extends MvvmBaseFragment<DevFragmentBedBreatheBinding, BedAndBreatheViewModel>
implements ILoadDataResult<BaseBean> {
    public final static String ARG_PARAM = "RadarBean";
    private RadarBean radarBean;
    private CustomTipsPopupWindow customTipsPopupWindow;


    public static DevBedAndBreatheFragment getInstance(RadarBean radarBean) {
        DevBedAndBreatheFragment fragment = new DevBedAndBreatheFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARG_PARAM, radarBean);
        fragment.setArguments(bundle);   //设置参数
        return fragment;
    }

    @Override
    protected void initParameters() {
        super.initParameters();
        Bundle bundle = getArguments();
        if (null != bundle) {
            radarBean = (RadarBean) bundle.getSerializable(ARG_PARAM);
        }
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //获得雷达Id
        Bundle bundle = getArguments();
        if (bundle != null) {
            //连接websockt同步心率、呼吸bpm值
            viewModel.setRadarId(radarBean.getRadarUuid());
            int radarState = radarBean.getRadarState();
            if(0==radarState){
//                viewModel.getIsDevOnLine().postValue(true);
                //在线
                viewDataBinding.devLayout.setVisibility(View.VISIBLE);
                viewDataBinding.devLayoutOffline.setVisibility(View.GONE);
                setLoadSir(viewDataBinding.devLayoutLoading);
                initView();
            }else{
                //离线
                viewDataBinding.devLayout.setVisibility(View.GONE);
                viewDataBinding.devLayoutOffline.setVisibility(View.VISIBLE);
            }
            ThreadPoolUtils.getInstance().execute(()-> {
                viewModel.getClient().jConnect();
            });

        }else{
            //离线
            viewDataBinding.devLayout.setVisibility(View.GONE);
            viewDataBinding.devLayoutOffline.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {
        viewModel.getIsInBed().observe(getViewLifecycleOwner(), aBoolean -> {
            if (aBoolean) {//在床上
                viewDataBinding.devImgStatusBg.setImageResource(R.drawable.dev_shape_round_blue);
                viewDataBinding.devImgStatus.setImageResource(R.mipmap.dev_icon_inbed);
            } else {//不在床上
                viewDataBinding.devImgStatusBg.setImageResource(R.drawable.dev_shape_round_gray2);
                viewDataBinding.devImgStatus.setImageResource(R.mipmap.dev_icon_notinbed);
            }
        });
        showLoading();
        viewModel.onLoad();
        if(radarBean.getType().get() == RadarType.WAVVE_PRO.get()){
            viewModel.getRadarTipsState((bean)->{
                if (bean.tipsState == 1) {
                    View v = ((ICustomToolBar) getActivity()).getCustomToolBar().getSettingIcon();
                    customTipsPopupWindow = CustomTipsPopupWindow.builder(getActivity())
                            .setLayoutRes(R.layout.common_popupwindow_tips)
                            .setWidth(SizeUtils.dp2px(138))
                            .setHeight(SizeUtils.dp2px(32))
                            .setParentView(((ICustomToolBar) getActivity()).getCustomToolBar())
                            .build();

                    v.post(()->{
                        customTipsPopupWindow.setShowBackgroundMask(false);
                        customTipsPopupWindow.showAsDropDown(v);
                    });
                }
            });
        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_bed_breathe;
    }

    @Override
    public int getBindingVariable() {
        return BR.data;
    }

    @Override
    protected BedAndBreatheViewModel getViewModel() {
        BaseViewModelFactroy<BaseBean> factroy = new BaseViewModelFactroy<>(null, this);
        BedAndBreatheViewModel tmp =  new ViewModelProvider(this, factroy).get(BedAndBreatheViewModel.class);
        return tmp;
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    public void setRightButtonConfigure(int imageId){
        ((ICustomToolBar) getActivity()).getCustomToolBar().setMySettingIcon(imageId);
        ((ICustomToolBar) getActivity()).getCustomToolBar().setSettingIconOnClickListener(v->{
            v.setVisibility(View.GONE);
            DevDeviceSettingsFragment fragment = DevDeviceSettingsFragment.getInstance(radarBean);
            FragmentUtil.add(getActivity(), ((IHostLayout) getActivity()).getContentId(), fragment, this, true);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if(getActivity()!=null){
            ((ITitle) getActivity()).setTitle(getString(R.string.dev_status_title));
            setRightButtonConfigure(R.mipmap.dev_icon_device_set);
        }
        JWebSocketClient client = viewModel.getClient();
        if(null != client && !client.isOpen() && !client.isReconnect() && client.isClosed()) {
            LogUtils.d("JWebSClient", "onResume--->jReconnect");
            viewModel.getClient().jReconnect();
        };
    }

    @Override
    public void onDestroy() {
        dismissSelectPopupWindow();
        if(null != viewModel.getClient()) {
            LogUtils.d("JWebSClient", "onDestroy --->closeConnectByUser");
            viewModel.getClient().closeConnectByUser();
        }
        super.onDestroy();

    }

    @Override
    public void onPause() {
        dismissSelectPopupWindow();
        super.onPause();
        if(null != viewModel.getClient()){
            LogUtils.d("JWebSClient", "onPause --->closeConnectByUser");
            viewModel.getClient().closeConnectByUser();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /** 隐藏选择弹窗 */
    private void dismissSelectPopupWindow(){
        if (null == customTipsPopupWindow) { return; }
        customTipsPopupWindow.dismiss();
    }


    @Override
    public void loadDataSuccess(BaseBean baseBean) {
        showContent();
    }



    @Override
    public void loadDataFail(String decs) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            dismissSelectPopupWindow();
            LogUtils.d("JWebSClient", "onHiddenChanged:hidden");
            if(null != viewModel.getClient()) {
                LogUtils.d("JWebSClient", "hidden --->closeConnectByUser");
                viewModel.getClient().closeConnectByUser();
            }
        } else {
            LogUtils.d("JWebSClient", "onHiddenChanged:show");
            if(null != viewModel.getClient()  && !viewModel.getClient().isOpen()) {
                LogUtils.d("JWebSClient", "show --->jReconnect");
                viewModel.getClient().jReconnect();
            }
        }
    }

}
